<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once 'Zend/Loader/Autoloader.php';

$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->setFallbackAutoloader(true);

try {
	// make sure the application is invoked the right way
	$opts = new Zend_Console_Getopt(
		array(
			'url|u=s'     => 'The URI for the file to be downloaded',
			'file|f=s'    => 'Local filename used for saving the resource',
			'chunk|c=i'   => 'Chunk size, in bytes',
			'limit|l=i'   => 'Maximum number of bytes to be downloaded',
			'dsource|d=s' => 'Path to the datasource'
	));
	$opts->parse();

	if (isset($opts->file)) {
		$application = new KChunk_Application($opts->url, $opts->file);
	} else {
		$application = new KChunk_Application($opts->url);
	}

	if (isset($opts->chunk)) {
		$application->setChunkSize($opts->chunk);
	}

	if (isset($opts->dsource)) {
		$application->setDatasourcePath($opts->dsource);
	}

	if (isset($opts->limit)) {
		$application->setDownloadLimit($opts->limit);
	}

	$application->initDatasource();
	$application->initDownloadPlan();
	$application->run();
	$application->cleanup();
} catch (Zend_Console_Getopt_Exception $e) {
	echo $e->getUsageMessage();
	exit;
} catch (Exception $e) {
	echo $e->getMessage();
	exit;
}